package com.ruoyi.dept.controller;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.ruoyi.common.core.service.UserService;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.demo.controller.TestExcelController;
import com.ruoyi.dept.domain.BsInstrument;
import com.ruoyi.dept.domain.bo.BsDepartmentBo;
import com.ruoyi.dept.domain.vo.BsDepartmentVo;
import com.ruoyi.dept.service.IBsDepartmentService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckLogin;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.dept.domain.vo.BsInstrumentVo;
import com.ruoyi.dept.domain.bo.BsInstrumentBo;
import com.ruoyi.dept.service.IBsInstrumentService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 试验室仪器
 *
 * @author zyb
 * @date 2024-04-22
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/dept/bsInstrument")
public class BsInstrumentController extends BaseController {

    private final IBsInstrumentService iBsInstrumentService;
    private final IBsDepartmentService iBsDepartmentService;

    /**
     * 查询试验室仪器列表
     */
    @SaCheckLogin
    @GetMapping("/list")
    public TableDataInfo<BsInstrumentVo> list(BsInstrumentBo bo, PageQuery pageQuery) {
        return iBsInstrumentService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出试验室仪器列表
     */
    @SaCheckLogin
    @Log(title = "试验室仪器", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(BsInstrumentBo bo, HttpServletResponse response) {
        List<BsInstrumentVo> list = iBsInstrumentService.queryList(bo);
        ExcelUtil.exportExcel(list, "试验室仪器", BsInstrumentVo.class, response);
    }

    /**
     * 获取试验室仪器详细信息
     *
     * @param instruId 主键
     */
    @SaCheckLogin
    @GetMapping("/{instruId}")
    public R<BsInstrumentVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long instruId) {
        return R.ok(iBsInstrumentService.queryById(instruId));
    }

    /**
     * 新增试验室仪器
     */
    @SaCheckLogin
    @Log(title = "试验室仪器", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody BsInstrumentBo bo) {
        return toAjax(iBsInstrumentService.insertByBo(bo));
    }

    /**
     * 修改试验室仪器
     */
    @SaCheckLogin
    @Log(title = "试验室仪器", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody BsInstrumentBo bo) {
        return toAjax(iBsInstrumentService.updateByBo(bo));
    }

    /**
     * 删除试验室仪器
     *
     * @param instruIds 主键串
     */
    @SaCheckLogin
    @Log(title = "试验室仪器", businessType = BusinessType.DELETE)
    @DeleteMapping("/{instruIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] instruIds) {
        return toAjax(iBsInstrumentService.deleteWithValidByIds(Arrays.asList(instruIds), true));
    }

    /**
     * 导入数据
     *
     * @param file 导入文件
     */
    @SaCheckLogin
    @Log(title = "试验室仪器", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file,String deptId, boolean updateSupport) throws Exception {
        ExcelResult<BsInstrumentVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), BsInstrumentVo.class, true);
        List<BsInstrumentVo> volist = excelResult.getList();
        List<BsInstrument> list = BeanUtil.copyToList(volist, BsInstrument.class);

        BsDepartmentBo bo = new BsDepartmentBo();
        bo.setDeptId(Long.valueOf(deptId));
        List<BsDepartmentVo> bsDepartmentVoList = iBsDepartmentService.queryList(bo);
        list.forEach(t ->{
            t.setDeptId(deptId);
            // 判断导入的科室名称是否存在
            if (!bsDepartmentVoList.stream().map(BsDepartmentVo :: getName).anyMatch(name ->name.equals(t.getDpmId()))){
                bo.setName(t.getDpmId());
                // 新增科室
                iBsDepartmentService.insertBsDepartmentByBo(bo);
                t.setDpmId(String.valueOf(bo.getId()));
                t.setDpmName(bo.getName());
            }else {
                Optional<BsDepartmentVo> first = bsDepartmentVoList.stream().filter(s -> s.getName().equals(t.getDpmId())).findFirst();
                BsDepartmentVo bsDepartmentVo = first.get();
                t.setDpmId(String.valueOf(bsDepartmentVo.getId()));
                t.setDpmName(bsDepartmentVo.getName());
            }

        });
        iBsInstrumentService.saveBatch(list, updateSupport);
        return R.ok(excelResult.getAnalysis());
    }


    /**
     * 导出试验室仪器模板
     */
    @SaCheckLogin
    @PostMapping("/exportTemplateOne")
    public void exportTemplateOne(HttpServletResponse response) {

        try {
            ExcelUtil.exportToTemplate(response,  "excel/试验室仪器模板.xlsx","试验室仪器模板", null,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 定时更新消息通知数据
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void updateOrInsertSysMessageScheduled(){
        iBsInstrumentService.updateOrInsertSysMessageScheduled();
    }
}
